const shell = require('shelljs')
const path = require("path")
const os = require('os')

const { get, mkDirsSync, writeFileData } = require('./common')
const { uniConfigLog } = require('./log')

const log = uniConfigLog

let CLI_PATH
let sysType = os.type()
if (sysType === 'Windows_NT') {
    CLI_PATH = 'cli'
} else {
    CLI_PATH = './cli'
}

log('环境', sysType, CLI_PATH)

const uploads = {
    async uploadWeixin(config, env, type, basePath) {
        // 微信项目源码路径
        const weixinDevtoolsPath = get(config, 'mp-weixin.ideDir')

        const EXEC_CODE_TYPE = env === 'development' ? 'dev' : 'build'
        const WEIXIN_PRESET_PATH = path.resolve(basePath, `./dist/${EXEC_CODE_TYPE}/${type}`)
        const VERSION = get(config, 'mp-weixin.version')
        const DESCRIPTION = get(config, 'mp-weixin.description', '') + '，cli-upload，env=' + global.NODE_ENV

        async function upload (resolve) {
            // 打开小程序项目
            const uploadShell = `${CLI_PATH} upload --project ${WEIXIN_PRESET_PATH} -v ${VERSION} -d '${DESCRIPTION}' --color=always`
            log('上传项目', WEIXIN_PRESET_PATH)
            console.log('\n')
            setTimeout(() => {
                shell.cd(weixinDevtoolsPath)
                // 上传
                shell.exec(uploadShell, (code, err) => {
                    resolve(code, err)
                    if (err && /登录/.test(err)) {
                        log('登录失效', '请扫描二维码登录开发者工具')
                        shell.exec(`${CLI_PATH} login -f terminal --qr-size small`)
                    }
                })
            }, 2000)
        }

        return new Promise(resolve => {
            if (VERSION) {
                upload(resolve)
            } else {
                log('未设置版本号，上传取消')
            }
        })
    }
}
module.exports = uploads
